package demo2.domain;

import demo2.domain.mapper.StudentMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Transactional(rollbackFor = RuntimeException.class)
@Service
public class StudentServiceImpl implements StudentService {
    private final StudentMapper studentMapper;

    public StudentServiceImpl(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }

    @Override
    public List<MaskedStudentRecord> findWithinLimit(Long firstId, Integer n) {
        List<Student> list = studentMapper.findWithinLimit(firstId, n);
        return list.stream().map(MaskedStudentRecord::new).collect(Collectors.toList());
    }

    @Override
    public List<MaskedStudentRecord> findAll() {
        List<Student> students = studentMapper.findAll();
        return students.stream().map(MaskedStudentRecord::new).collect(Collectors.toList());
    }

    @Override
    public Optional<MaskedStudentRecord> findById(Long id) {
        MaskedStudentRecord result;
        Optional<Student> found = studentMapper.findById(id);
        if (found.isPresent()) {
            result = new MaskedStudentRecord(found.get());
        } else {
            return Optional.empty();
        }
        return Optional.of(result);
    }

    @Override
    public void save(Student student) {
        if (student.getId() != null) {
            studentMapper.modify(student);
            return;
        }
        studentMapper.create(student);
    }

}
